//
//  OAuthViewController.swift
//  Super_WeiBo
//
//  Created by SuperMac on 16/3/21.
//  Copyright © 2016年 lc. All rights reserved.
//
// Sina微博帐号
// App Key：2312786413
// App Secret：01bcf8c18e9aa057394cae4298cc6fa5
// 登录授权界面
//https://api.weibo.com/oauth2/authorize?client_id=2312786413&redirect_uri=http://www.baidu.com

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    let WB_App_Key = "2312786413"
    let WB_App_Secret = "01bcf8c18e9aa057394cae4298cc6fa5"
    let WB_redirect_uri = "http://www.baidu.com"
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 初始化导航条
        navigationItem.title = "陈馆长的私人订制"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(OAuthViewController.closeOAuthVC))
        
        // 打开登录界面
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_Key)&redirect_uri=\(WB_redirect_uri)"
        let url = NSURL(string: urlStr)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    /**
     关闭按钮点击事件
     */
    func closeOAuthVC() {
        dismissViewControllerAnimated(true, completion: nil)
    }

    // MARK: - 懒加载
    private lazy var webView : UIWebView = {
        let wv = UIWebView()
        wv.delegate = self
        return wv
    }()
}

extension OAuthViewController : UIWebViewDelegate
{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        let urlStr = request.URL?.absoluteString
        // 登录成功
        if !(urlStr!.hasPrefix(WB_redirect_uri))
        {
            return true
        }
        
        let codeStr = "code="
        if request.URL!.query!.hasPrefix(codeStr)
        {// 授权成功
            let code = request.URL!.query?.substringFromIndex(codeStr.endIndex)
            loadAccessToken(code!)
        }
        else
        {// 取消授权
            // 关闭授权页面
            closeOAuthVC()
        }
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView)
    {// 提示用户正在加载
        SVProgressHUD.showInfoWithStatus("努力加载中...", maskType: SVProgressHUDMaskType.Black)
    }
    func webViewDidFinishLoad(webView: UIWebView)
    {// 提示用户加载完成
        SVProgressHUD.dismiss()
    }
    
    /**
     获取AccessToken
     
     - parameter code: 已经授权的RequestToken
     */
    private func loadAccessToken(code : String)
    {
        // 接口
        let path = "oauth2/access_token"
        
        // 封装参数
        let params = ["client_id":WB_App_Key,"client_secret":WB_App_Secret,"grant_type":"authorization_code","code":code,"redirect_uri":WB_redirect_uri];
        
        // 发送post请求
        NetworkTools.shareNetworkTools().POST(path, parameters: params, success: { (_, JSON) -> Void in
            // 给account相关参数赋值 通过KVC
            let account = UserAccount(dict: JSON as! [String : AnyObject])
            // 获取用户信息
            account.loadUserInfo({ (account, error) -> () in
                if account != nil
                {
                    account?.saveAccount()
                    SVProgressHUD.showInfoWithStatus("授权成功", maskType: SVProgressHUDMaskType.Black)
                    NSNotificationCenter.defaultCenter().postNotificationName(Super_ChaoSwitchRootControllerKey, object: false)
                    return
                }
                SVProgressHUD.showInfoWithStatus("网络不给力", maskType: SVProgressHUDMaskType.Black)
            })
            
            }) { (_, error) -> Void in
                print(error)
        }
    }
}
